<template>
    <div class="consultation-container accident-theme">
      <div class="header-section">
        <h1><i class="el-icon-warning"></i> 事故保险专业咨询</h1>
        <p class="subtitle">为您提供7×24小时事故保险专业咨询服务</p>
      </div>
      
      <div class="chat-container">
        <div class="message-history" ref="messageContainer">
          <div v-for="(msg, index) in messages" :key="index" 
               :class="['message', msg.role]">
            <div class="message-avatar">
              <el-avatar v-if="msg.role === 'user'" :size="36" :src="userAvatar" />
              <el-avatar v-else :size="36" :src="assistantAvatar" />
            </div>
            <div class="message-content-wrapper">
              <div class="message-header">
                <span class="sender-name">{{ msg.role === 'user' ? '您' : '事故保险顾问' }}</span>
                <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
              </div>
              <div class="message-content" v-html="formatMessage(msg.content)"></div>
              <div v-if="msg.sources && msg.sources.length" class="message-sources">
                <div class="sources-title">相关条款:</div>
                <div class="sources-tags">
                  <el-tag 
                    v-for="(source, i) in msg.sources" 
                    :key="i" 
                    type="warning"
                    size="small"
                    effect="plain"
                    @click="showClauseDetail(source)"
                  >
                    <i class="el-icon-document"></i> {{ source }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
          
          <div v-if="loading" class="loading-indicator">
            <el-icon class="is-loading"><el-icon-loading /></el-icon>
            <span>正在分析您的问题...</span>
          </div>
        </div>
        
        <div class="input-section">
          <div class="input-area">
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              :autosize="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入您的事故保险相关问题，例如：交通事故如何理赔？"
              resize="none"
              @keyup.enter.native="handleKeyEnter"
            ></el-input>
            <div class="action-buttons">
              <el-button 
                type="warning" 
                @click="sendMessage"
                :loading="loading"
                class="send-button"
                round
              >
                <template #icon>
                  <el-icon><el-icon-send /></el-icon>
                </template>
                发送
              </el-button>
              <el-button 
                type="info" 
                @click="clearConversation"
                plain
                round
              >
                <template #icon>
                  <el-icon><el-icon-delete /></el-icon>
                </template>
                清空
              </el-button>
            </div>
          </div>
          
          <div class="quick-questions">
            <h4><i class="el-icon-collection-tag"></i> 常见问题快速提问:</h4>
            <div class="quick-tags">
              <el-tag
                v-for="(question, idx) in quickQuestions"
                :key="idx"
                type="warning"
                effect="dark"
                @click="quickAsk(question)"
                class="quick-tag"
              >
                {{ question }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
  
      <!-- 条款详情对话框 -->
      <el-dialog
        v-model="clauseDialogVisible"
        :title="selectedClause"
        width="60%"
        top="5vh"
      >
        <div class="clause-detail-content">
          <h3>条款内容详情</h3>
          <div class="clause-text">
            {{ getClauseContent(selectedClause) }}
          </div>
          <div class="clause-footer">
            <el-button type="warning" @click="clauseDialogVisible = false">关闭</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick } from 'vue'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  
  // 用户和助手头像
  const userAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  const assistantAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  
  const userInput = ref('')
  const loading = ref(false)
  const messages = ref([
    {
      role: 'assistant',
      content: '您好！我是事故保险AI顾问，可以为您解答关于交通事故理赔、意外伤害保障、理赔流程等问题。请问您想了解什么？',
      sources: ['【条款001】交通事故责任认定', '【条款005】意外伤害赔偿标准'],
      timestamp: new Date()
    }
  ])
  
  const quickQuestions = ref([
    '交通事故如何申请理赔？',
    '哪些事故不在保险范围内？',
    '理赔需要准备哪些材料？',
    '保险赔付多久能到账？',
    '第三方责任如何认定？'
  ])
  
  const messageContainer = ref(null)
  const clauseDialogVisible = ref(false)
  const selectedClause = ref('')
  
  // 模拟条款内容库
  const clauseLibrary = {
    '【条款001】交通事故责任认定': '根据《道路交通安全法》第七十六条...详细责任认定标准...',
    '【条款005】意外伤害赔偿标准': '意外伤害保险赔偿标准根据伤残等级划分...',
    // 可以添加更多条款
  }
  
  const formatMessage = (text) => {
    // 高亮显示条款引用
    return text.replace(/【条款[0-9]+】/g, '<span class="clause-highlight">$&</span>')
  }
  
  const formatTime = (date) => {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  }
  
  const scrollToBottom = () => {
    nextTick(() => {
      if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight
      }
    })
  }
  
  const sendMessage = async () => {
    if (!userInput.value.trim()) {
      ElMessage.warning('请输入咨询问题')
      return
    }
    
    try {
      loading.value = true
      
      // 添加用户消息
      messages.value.push({
        role: 'user',
        content: userInput.value,
        sources: [],
        timestamp: new Date()
      })
      
      scrollToBottom()
      
      // 调用API
      const response = await axios.post('http://127.0.0.1:8000/ai/session/', {
        insurance_type: 'accident',
        question: userInput.value
      })
      
      // 添加AI回复
      messages.value.push({
        role: 'assistant',
        content: response.data.answer,
        sources: response.data.sources || [],
        timestamp: new Date()
      })
      
      userInput.value = ''
      scrollToBottom()
    } catch (error) {
      ElMessage.error('咨询失败: ' + (error.response?.data?.message || error.message))
      
      // 添加错误提示消息
      messages.value.push({
        role: 'assistant',
        content: '抱歉，处理您的请求时出现问题，请稍后再试或联系客服。',
        sources: [],
        timestamp: new Date()
      })
      
      scrollToBottom()
    } finally {
      loading.value = false
    }
  }
  
  const handleKeyEnter = (e) => {
    if (e.shiftKey) {
      // Shift+Enter换行
      return
    }
    // 普通Enter发送消息
    e.preventDefault()
    sendMessage()
  }
  
  const quickAsk = (question) => {
    userInput.value = question
    sendMessage()
  }
  
  const clearConversation = () => {
    messages.value = [
      {
        role: 'assistant',
        content: '您好！我是事故保险AI顾问，可以为您解答关于交通事故理赔、意外伤害保障、理赔流程等问题。请问您想了解什么？',
        sources: [],
        timestamp: new Date()
      }
    ]
  }
  
  const showClauseDetail = (clause) => {
    selectedClause.value = clause
    clauseDialogVisible.value = true
  }
  
  const getClauseContent = (clause) => {
    return clauseLibrary[clause] || '暂无此条款的详细内容'
  }
  
  onMounted(() => {
    scrollToBottom()
  })
  </script>
  
  <style scoped>
  .consultation-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
    height: 90vh;
    display: flex;
    flex-direction: column;
  }
  
  .accident-theme {
    background-color: #fff9e6;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  }
  
  .header-section {
    text-align: center;
    margin-bottom: 20px;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  h1 {
    color: #e6a23c;
    margin-bottom: 5px;
    font-size: 24px;
  }
  
  .subtitle {
    color: #909399;
    font-size: 14px;
    margin: 0;
  }
  
  .chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
  
  .message-history {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 20px;
    padding: 15px;
    border-radius: 8px;
    background-color: #fafafa;
    scroll-behavior: smooth;
  }
  
  .message {
    display: flex;
    margin-bottom: 20px;
    max-width: 85%;
  }
  
  .message.user {
    margin-left: auto;
    flex-direction: row-reverse;
  }
  
  .message-avatar {
    margin-right: 12px;
    margin-left: 12px;
    flex-shrink: 0;
  }
  
  .message-content-wrapper {
    flex: 1;
  }
  
  .message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 6px;
  }
  
  .sender-name {
    font-weight: bold;
    color: #e6a23c;
  }
  
  .message-time {
    font-size: 12px;
    color: #999;
  }
  
  .message-content {
    padding: 12px 15px;
    border-radius: 12px;
    line-height: 1.6;
    word-break: break-word;
  }
  
  .message.user .message-content {
    background-color: #f5f5f5;
    border-top-right-radius: 0;
  }
  
  .message.assistant .message-content {
    background-color: #fdf6ec;
    border-top-left-radius: 0;
  }
  
  .message-sources {
    margin-top: 10px;
    padding-top: 8px;
    border-top: 1px dashed #eee;
  }
  
  .sources-title {
    font-size: 12px;
    color: #999;
    margin-bottom: 5px;
  }
  
  .sources-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .clause-highlight {
    color: #e6a23c;
    font-weight: bold;
    cursor: pointer;
    text-decoration: underline;
  }
  
  .input-section {
    border-top: 1px solid #f0f0f0;
    padding-top: 15px;
  }
  
  .input-area {
    margin-bottom: 15px;
  }
  
  .action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 10px;
  }
  
  .send-button {
    min-width: 100px;
  }
  
  .quick-questions {
    margin-top: 15px;
  }
  
  .quick-questions h4 {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    color: #666;
    font-size: 14px;
  }
  
  .quick-questions h4 i {
    margin-right: 5px;
  }
  
  .quick-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .quick-tag {
    cursor: pointer;
    transition: all 0.3s;
  }
  
  .quick-tag:hover {
    transform: translateY(-2px);
  }
  
  .loading-indicator {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 15px;
    color: #999;
  }
  
  .loading-indicator i {
    margin-right: 8px;
  }
  
  /* 条款详情对话框样式 */
  .clause-detail-content {
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .clause-detail-content h3 {
    color: #e6a23c;
    margin-bottom: 15px;
    text-align: center;
  }
  
  .clause-text {
    padding: 15px;
    background-color: #fafafa;
    border-radius: 8px;
    line-height: 1.8;
  }
  
  .clause-footer {
    margin-top: 20px;
    text-align: center;
  }
  
  /* 响应式调整 */
  @media (max-width: 768px) {
    .consultation-container {
      padding: 10px;
      height: 95vh;
    }
    
    .message {
      max-width: 90%;
    }
  }
  </style>